const network = require('../../utils/network')

Page({
  data: {
    phoneText: '',
    passwordText: '',
    loginStatus: 0 // 0 未登录，1 登录中
  },
  onLoad() {
    wx.setNavigationBarTitle({
      title: '欢迎登录'
    })
    wx.removeStorageSync('sessionId')

    let user = wx.getStorageSync('user')
    if (user) {
      this.setData({
        phoneText: user.tel
      })
    }
  },

  /**
   * @desc 验证
   */
  validate() {
    let phoneReg = /^1\d{10}$/
    let passwordReg = /^\w{6,16}$/

    // 电话号码格式检测
    if (!phoneReg.test(this.data.phoneText.trim())) {
      wx.showModal({
        title: '提示',
        content: '请填写正确的手机号',
        showCancel: false
      })
      return false
    }
    // 密码格式检测
    if (!passwordReg.test(this.data.passwordText.trim())) {
      wx.showModal({
        title: '提示',
        content: '请填写 6 至 16 位密码',
        showCancel: false
      })
      return false
    }

    return true
  },

  /**
   * @desc 登录
   */
  login() {
    if (this.validate()) {
      let params = {
        username: 'S' + this.data.phoneText.trim(),
        password: this.data.passwordText.trim()
      }
      network
        .post('user/login', params, '登录中...')
        .then(data => {
          if (data.user.roleId !== 28) {
            wx.showModal({
              title: '错误',
              content: '用户名或密码错误!',
              showCancel: false
            })
            return
          }

          // 用户信息
          wx.setStorageSync('user', data.user)
          // 保持会话
          wx.setStorageSync('sessionId', data.sessionId)

          if (this.checkHasRule()) {
            wx.navigateTo({
              url: '/pages/sudoku/sudoku'
            })
          }
        })
        .catch((...args) => {
          console.log(args)
          wx.showModal({
            title: '错误',
            content: '用户名或密码错误!',
            showCancel: false
          })
        })
    }
  },

  /**
   * @desc 手机号失焦
   * @param e
   */
  phoneBlur(e) {
    let phoneText = e.detail.value.trim()
    this.setData({
      phoneText
    })
  },

  /**
   * @desc 密码输入
   * @param e
   */
  passwordInput(e) {
    let passwordText = e.detail.value.trim()
    this.setData({
      passwordText
    })
  },

  /**
   * @desc 去注册
   */
  toRegister() {
    wx.navigateTo({
      url: '/pages/register/register'
    })
  },

  /**
   * @desc 去注册
   */
  toFind() {
    wx.navigateTo({
      url: '/pages/find/find'
    })
  },

  /**
   * @desc 去游戏
   */
  toGame() {
    if (this.checkHasRule()) {
      wx.navigateTo({
        url: '/pages/sudoku/sudoku'
      })
    }
  },

  /**
   * @desc 判断是否看了规则
   */
  checkHasRule() {
    let hasRule = wx.getStorageSync('hasRule')
    if (!hasRule) {
      wx.setStorageSync('hasRule', true)
      wx.navigateTo({
        url: '/pages/rule/rule'
      })
      return false
    }
    return true
  }
})
